﻿(function ($) {

    $(function () {
        var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
        $.getScript(scriptbase + "SP.js", function () {
            $.getScript(scriptbase + "SP.Taxonomy.js", getPictureGallery());

        });
    });

    this.getPictureGallery = function () {

        $('#pictureGalleryloading').show();
        var currentId = 'pictureGallery';
        var itemrowlimit = getRowLimitFromContentEditorWP(currentId);

        var galleryClientContext = new SP.ClientContext.get_current();
        var galleryList = galleryClientContext.get_web().get_lists().getByTitle('Gallery');
        var gallerycamlQuery = new SP.CamlQuery();
        gallerycamlQuery.set_viewXml('<View><Query><Where><IsNotNull><FieldRef Name=\'FileLeafRef\' /></IsNotNull></Where><OrderBy><FieldRef Name=\'Modified\' Ascending=\'FALSE\' /></OrderBy></Query> <ViewFields><FieldRef Name=\'FileLeafRef\' /><FieldRef Name=\'LinkFilename\' /><FieldRef Name=\'Title\' /></ViewFields> <RowLimit>' + itemrowlimit + '</RowLimit> </View>');
        var galleryItems = galleryList.getItems(gallerycamlQuery);

        galleryClientContext.load(galleryItems);
        galleryClientContext.executeQueryAsync(
            function () {
                $('#pictureGalleryloading').hide();
                var gallerylistEnumerator = galleryItems.getEnumerator();
                var albumCollection = [];
                while (gallerylistEnumerator.moveNext()) {

                    var galleryitem = gallerylistEnumerator.get_current();

                    var folderPath = galleryitem.get_item("FileRef");
                    var folderName = galleryitem.get_item("FileLeafRef");

                    //Push root folders in json array
                    albumCollection.push({ folderName: folderName, folderPath: folderPath });
                }

                // get images in corresponding folder
                if (albumCollection.length > 0) {
                    getImageCollection(albumCollection);
                }
            }, function (sender, args) {
                alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        );
    };

    this.getImageCollection = function (albumCollection) {
        var galleryImagesClientContext = new SP.ClientContext.get_current();
        var galleryImagesList = galleryImagesClientContext.get_web().get_lists().getByTitle('Gallery');
        var galleryImagescamlQuery = new SP.CamlQuery();
        galleryImagescamlQuery.set_viewXml("<View Scope='RecursiveAll'><Query><Where><And><IsNotNull><FieldRef Name='ID' /></IsNotNull><Eq><FieldRef Name='IsAvatar' /><Value Type='Boolean'>1</Value></Eq></And></Where><OrderBy><FieldRef Name='Modified' Ascending='FALSE'/></OrderBy></Query><ViewFields><FieldRef Name='ID' /><FieldRef Name='IsAvatar' /><FieldRef Name='FileLeafRef' /><FieldRef Name='LinkFilenameNoMenu' /><FieldRef Name='Title' /><FieldRef Name='FileRef' /></ViewFields></View>");
        var galleryImagesItems = galleryImagesList.getItems(galleryImagescamlQuery);

        galleryImagesClientContext.load(galleryImagesItems);
        galleryImagesClientContext.executeQueryAsync(
            function () {
                var galleryImagesEnumerator = galleryImagesItems.getEnumerator();
                var imagesCollection = [];
                while (galleryImagesEnumerator.moveNext()) {

                    var galleryImagesitem = galleryImagesEnumerator.get_current();

                    var title = galleryImagesitem.get_item("Title");
                    var isAvatar = galleryImagesitem.get_item("IsAvatar");
                    var itemId = galleryImagesitem.get_item("ID");
                    var imageName = galleryImagesitem.get_item("FileLeafRef");
                    var imagePath = galleryImagesitem.get_item("FileRef");

                    //Push image collection in json array
                    imagesCollection.push({ title: title, isAvatar: isAvatar, itemId: itemId, imageName: imageName, imagePath: imagePath });
                }

                // Compare json to get items
                if (albumCollection.length > 0) {

                    var defaultAbumImagePath = '/teams/OurVoiceHN/Style Library/Images/default_image.gif';
                    var imageGalleryContent = '';
                    var activeCount = 0;
                    var activeClass = "active item";
                    $.each(albumCollection, function (indexx, rootfolderx) {
                        activeCount++;
                        activeClass = (activeCount == 1) ? "active item" : "item";
                        var rootFolderPath = rootfolderx.folderPath;
                        var rootfolderName = rootfolderx.folderName;
                        var iconofFolder = defaultAbumImagePath;
                        var folderFullPath = window.location.protocol + '//' + window.location.host + rootFolderPath;
                        var tempIcon = "<div class='" + activeClass + "'><a href='" + folderFullPath + "'><img class=\"pic-image img-responsive\" src='" + iconofFolder + "' alt='" + rootfolderName + "' /></a><div class=\"picTitle\"><a href='" + folderFullPath + "'>" + rootfolderName + "</a></div></div>";

                        //filter array with rootfolder
                        var filteredArray = imagesCollection.filter(function (item) { return item.imagePath.toUpperCase().indexOf(rootFolderPath.toUpperCase()) !== -1; });
                        if (filteredArray.length > 0) {
                            $.each(filteredArray, function (index, imagescol) {
                                //get icon of folder
                                iconofFolder = imagescol.imagePath;
                                tempIcon = "<div class='" + activeClass + "'><a href='" + folderFullPath + "'><img class=\"pic-image img-responsive\" src='" + iconofFolder + "' alt='" + rootfolderName + "' /></a><div class=\"picTitle\"><a href='" + folderFullPath + "'>" + rootfolderName + "</a></div></div>";
                                return false;
                            });
                        }
                        imageGalleryContent += tempIcon;
                    });

                    $('#myCarouselGallery > .carousel-inner').html(imageGalleryContent);
                    makeSlidePictureGallery();
                }
            }, function (sender, args) {
                alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        );
    };

    function makeSlidePictureGallery() {
        $("#pictureGallery").hover(function () {
            $('#pictureGallery a.left').removeClass("hide");
            $('#pictureGallery a.right').removeClass("hide");
        }, function () {
            $('#pictureGallery a.left').addClass("hide");
            $('#pictureGallery a.right').addClass("hide");
        });
    }
}).call(this, jQuery);